package com.itheima.service;


import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import com.itheima.common.SnowFlake;
import com.itheima.mapper.client.UserMapper;
import com.itheima.pojo.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * @author ChenJunJie
 * @date 2022/6/18 17:23
 * 用户service层
 */
@Service
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private UserMapper userMapper;

    //用户登录
    public LoginVo login(LoginDto loginDto){

        String codeNum = redisTemplate.opsForValue().get(loginDto.getPhone());

        //响应类
        LoginVo loginVo = new LoginVo();

         if (loginDto.getCode().equals(codeNum)){

             //查询当前电话是否拥有用户，如果有则直接登录
             SelectUserByPhoneDto user = new SelectUserByPhoneDto();
             user.setPhone(loginDto.getPhone());
             SelectUserByPhoneDto selectUserByPhoneDto = userMapper.selectUserByPhone(user);
             if (selectUserByPhoneDto!=null){
                 //如果有用户，则将用户信息写入响应类中
                 //设置用户电话
                 loginVo.setPhone(selectUserByPhoneDto.getPhone());

                 //设置用户id
                 loginVo.setId(selectUserByPhoneDto.getId());

                 //设置用户token
                 String s = System.currentTimeMillis() + selectUserByPhoneDto.getId();
                 String token = DigestUtils.md5DigestAsHex(s.getBytes());
                 loginVo.setToken(token);

                 //传token进redis
                 redisTemplate.opsForValue().set(token, selectUserByPhoneDto.getId(), 1, TimeUnit.DAYS);

                 //设置用户状态
                 loginVo.setStatus(selectUserByPhoneDto.getStatus());

                 return loginVo;
             }else {
                 //如果没有则创建一个用户
                 AddUserDto u = new AddUserDto();
                 long id = snowFlake.nextId();
                 u.setId(id+"");
                 u.setPhone(loginDto.getPhone());
                 //随机一个4位数
                 Random random = new Random();
                 int num = random.nextInt(9000) + 1000;
                 u.setUsername("默认用户"+num);

                 //判断用户是否创建成功
                 int i = userMapper.addUser(u);
                 if (i>0){
                     SelectUserByPhoneDto userSelect = new SelectUserByPhoneDto();
                     userSelect.setPhone(loginDto.getPhone());
                     SelectUserByPhoneDto selectUser = userMapper.selectUserByPhone(user);

                     //设置用户电话
                     loginVo.setPhone(selectUser.getPhone());

                     //设置用户id
                     loginVo.setId(selectUser.getId());

                     //设置用户token
                     String s = System.currentTimeMillis() + selectUser.getId();
                     String token = DigestUtils.md5DigestAsHex(s.getBytes());
                     loginVo.setToken(token);

                     //传token进redis
                     redisTemplate.opsForValue().set(token, selectUser.getId(), 1, TimeUnit.DAYS);

                     //设置用户状态
                     loginVo.setStatus(selectUser.getStatus());
                 }
                 return loginVo;
             }
         }else {
             return null;
         }
    }

    //用户登出
    public void loginOut (HttpServletRequest request){
        String token = request.getHeader("AuthorizationUser");

        if (token != null && !"".equals(token)) {

            //删除手机验证码
            String userId = redisTemplate.opsForValue().get(token);

            //查询对应的user信息
            if (userId!=null){
                SelectUserById user = userMapper.selectUserById(userId);
                redisTemplate.delete(user.getPhone());
            }

            //删除用户token
            redisTemplate.delete(token);
        }
    }

    //短信验证码发送
    public boolean sendMsg (SendMsgDto sendMsgDto) throws Exception {
        // //设置配置
        // Config config= new Config()
        //         .setAccessKeyId("LTAI5tHNZ7C2S1vjid1CGknF")
        //         .setAccessKeySecret("xbhWXqNCg71PjDUPOYxTwL0QORVOl4");
        // config.endpoint= "dysmsapi.aliyuncs.com";
        //
        // //设置用户
        // Client client = new Client(config);
        //
        // //设置短信随机数
        // Random random = new Random();
        // int i = random.nextInt(9000) + 1000;
        //
        // //设置发送短息的信息
        // SendSmsRequest sendSmsRequest = new SendSmsRequest()
        //         .setSignName("阿里云短信测试")
        //         .setTemplateCode("SMS_154950909")
        //         .setPhoneNumbers(sendMsgDto.getPhone())
        //         .setTemplateParam("{\"code\":\""+i+"\"}");
        //
        //
        // RuntimeOptions runtime = new RuntimeOptions();
        // try {
        //     client.sendSmsWithOptions(sendSmsRequest, runtime);
        //
        //     //将手机号与验证码存入token中
        //     redisTemplate.opsForValue().set(sendMsgDto.getPhone(),i+"",5, TimeUnit.MINUTES);
        //
        // } catch (TeaException error) {
        //     com.aliyun.teautil.Common.assertAsString(error.message);
        //     return false;
        // } catch (Exception e) {
        //     TeaException error = new TeaException(e.getMessage(), e);
        //     com.aliyun.teautil.Common.assertAsString(error.message);
        //     return false;
        // }

        //设置短信随机数
        Random random = new Random();
        int i = random.nextInt(9000) + 1000;
        redisTemplate.opsForValue().set(sendMsgDto.getPhone(),i+"",5, TimeUnit.MINUTES);
        return true;
    }
}
